/*eslint-disable*/
import { ElMessage } from "element-plus";
import mainApi from "@/api/mainApi.js";
import uploadApi from "@/api/uploadApi.js";

const path = window.myApi.path;
const fs = window.myApi.fs;

export default {
    // 更新面补
    async faceRenew(fileHouse, renewFolder) {
        return new Promise(async (res, rej) => {
            try {
                // 读取更新包的所有面补名称
                let renewFaceList = await this.readFaceName(renewFolder);

                let renewFolderList = await fs.promises.readdir(renewFolder);

                for (let renewIndex = 0; renewIndex < renewFaceList.length; renewIndex++) {
                    let face = renewFaceList[renewIndex];
                    // 读取当前所有面补名称
                    let currentFaceList = await this.readFaceName(path.join(fileHouse, "face"));
                    // 判断是否是新面补
                    let newFaceCheckResult = this.isNewFace(currentFaceList, face);
                    let isNew = newFaceCheckResult.isNew;
                    let faceIndex = newFaceCheckResult.faceIndex;
                    // 更新包中的面补集路径
                    let newFaceSet = path.join(renewFolder, renewFolderList[renewIndex]);

                    if (isNew) {
                        // 新增面补
                        let targetPath = path.join(fileHouse, "face", renewFolderList[renewIndex]);
                        await this.addFace(targetPath, newFaceSet);
                    } else {
                        // 追加面补
                        let faceSetPath = (await fs.promises.readdir(path.join(fileHouse, "face")))[faceIndex];
                        await this.appendFace(faceSetPath, newFaceSet);
                    }
                }

                // 顺利完成
                res();
            } catch (err) {
                // 捕获错误并传递错误信息
                console.error('面补更新失败:', err);
                ElMessage.error(`面补更新失败: ${err.message}`);
                rej(err);
            }
        });
    },
    // 读取当前的所有面补名称
    readFaceName(facePath) {
        try {
            const nameList = [];
            const files = fs.readdirSync(facePath);

            for (const folder of files) {
                const subDir = path.join(facePath, folder);
                const subFiles = fs.readdirSync(subDir);

                if (subFiles.length === 0) {
                    console.warn(`子目录 ${folder} 为空`);
                    continue;
                }

                const faceSet = subFiles[0];
                const name = this.splitFaceName(faceSet);
                nameList.push(name);
            }

            return nameList
        } catch (err) {
            ElMessage.error(`读取当前面补名称失败: ${err.message}`);
        }
    },
    // 判断是否为新面补
    isNewFace(currentFaceList, newFace) {
        let isNew = true
        let faceIndex = 0;
        for (const name of currentFaceList) {
            if (name === newFace) {
                isNew = false
                break
            }
            faceIndex++
        }
        return { isNew, faceIndex }
    },
    // 提取面补名称
    splitFaceName(folder) {
        try {
            const parts = folder.split(" ");
            if (parts.length < 2) {
                throw new Error("文件名缺少空格分隔符");
            }
            return parts[1].split("面补")[0].split("身形")[0] || "未知名称";
        } catch (err) {
            console.error(`解析文件名 ${folder} 失败:`, err);
            return "格式错误";
        }
    },
    // 新增面补
    async addFace(targetPath, facePath) {
        return new Promise(async (res, rej) => {
            try {
                // 异步读取源文件夹内容
                const faceList = await fs.promises.readdir(facePath);
                for (const face of faceList) {
                    // 将新面补集复制至数据包中
                    await this.copyFolderAsync(facePath, targetPath);
                    // 消息发布
                    ElMessage({ message: `${face}转存成功` });
                }
                res();
            } catch (err) {
                rej(err);
            }
        });
    },
    // 追加面补
    async appendFace(faceSet, facePath) {
        return new Promise(async (res, rej) => {
            try {
                // 异步读取待追加的面补
                const faceList = await fs.promises.readdir(facePath);
                for (const face of faceList) {
                    // 组装describeList
                    let describeList = [
                        {
                            name: "所属球员",
                            data: faceSet + "|"
                        },
                        {
                            name: "资源名称",
                            data: face.split(" ")[1]
                        },
                        {
                            name: "资源作者",
                            data: face.split(" ")[2]
                        }
                    ];
                    // 组装fileList
                    let fileList = [
                        {
                            name: "_png.iff",
                            filePath: this.faceFileSplit(path.join(facePath, face), "png")
                        },
                        {
                            name: "_face.iff",
                            filePath: this.faceFileSplit(path.join(facePath, face), "face")
                        },
                        {
                            name: "预览图.jpg",
                            filePath: path.join(path.join(facePath, face), "preview", "preview.jpg")
                        }
                    ];
                    console.log(describeList, fileList);
                    // 执行替换
                    await uploadApi.uploadFileRun(fileList, describeList, "face");
                }
                res();
            } catch (err) {
                rej(err);
            }
        });
    },
    // 面补文件类型分发
    faceFileSplit(folderPath, keyWord1) {
        for (const file of fs.readdirSync(folderPath)) {
            if (file.indexOf(keyWord1) != -1) {
                return path.join(folderPath, file)
            }
        }
    },
    // 文件夹复制
    async copyFolderAsync(src, dest) {
        return new Promise(async (res, rej) => {
            try {
                // 创建目标文件夹（如果不存在）
                if (!fs.existsSync(dest)) {
                    fs.mkdirSync(dest, { recursive: true });
                    mainApi.writeDailyLog(`文件夹创建成功：${dest}`);
                }

                // 异步读取源文件夹内容
                const entries = await fs.promises.readdir(src);

                for (const entry of entries) {
                    const srcPath = path.join(src, entry);
                    const destPath = path.join(dest, entry);

                    if (entry.indexOf(".") === -1) {
                        // 递归复制子目录
                        await this.copyFolderAsync(srcPath, destPath);
                    } else {
                        // 直接复制文件
                        await fs.promises.copyFile(srcPath, destPath);
                        mainApi.writeDailyLog(`文件转存成功：${srcPath}-->${destPath}`);
                    }
                }
                res();
            } catch (err) {
                rej(err);
            }
        });
    },
    // 其余类型mod转存
    commonRenew(fileHouse, renewFolder) {
        // 确定文件类型
        let modType = path.basename(renewFolder)
        // 目标文件夹路径
        let targetPath = path.join(fileHouse, modType)
        // 执行替换
        this.addFace(targetPath, renewFolder)
    }
};